<template>
  <div class="tool-config-container">
    <div class="config-sidebar">
      <div class="sidebar-header">
        <h3>工具管理</h3>
        <div class="header-actions">
          <el-button type="primary" size="small" @click="createNewConfig">
            <el-icon><Plus /></el-icon> 新建工具
          </el-button>
          <el-button type="success" size="small" @click="manageCategoriesDialog = true">
            <el-icon><Setting /></el-icon> 分类管理
          </el-button>
        </div>
      </div>

      <div class="config-list" v-loading="loadingList">
        <div v-for="category in groupedTools" :key="category.name" class="category-group">
          <div class="category-title">{{ category.name }}</div>
          <div
            v-for="tool in category.tools"
            :key="tool.id"
            :class="['config-item', { active: currentConfig?.id === tool.id }]"
            @click="selectConfig(tool)"
          >
            <div class="config-item-header">
              <span class="config-name">{{ tool.name }}</span>
              <el-tag v-if="!tool.is_enabled" type="info" size="small" effect="dark">已禁用</el-tag>
            </div>
            <div class="config-desc">{{ tool.description || '暂无描述' }}</div>
          </div>
        </div>
      </div>
    </div>

    <div class="config-main">
      <template v-if="currentConfig">
        <div class="main-header">
          <h2>{{ isEditing ? '编辑工具' : '新建工具' }}</h2>
          <div class="actions">
            <el-button type="primary" @click="saveConfig">保存</el-button>
            <el-button v-if="currentConfig.id" type="danger" @click="deleteConfig">删除</el-button>
          </div>
        </div>

        <el-form :model="formData" label-position="top" class="config-form">
          <el-form-item label="工具Key" required>
            <el-input v-model="formData.key" placeholder="data_query" :disabled="isEditing" />
          </el-form-item>

          <el-form-item label="工具名称" required>
            <el-input v-model="formData.name" placeholder="数据查询工具" />
          </el-form-item>

          <el-form-item label="描述">
            <el-input v-model="formData.description" placeholder="查询数据库中的业务数据" />
          </el-form-item>

          <el-form-item label="分类" required>
            <el-select v-model="formData.category" placeholder="选择分类" filterable>
              <el-option v-for="cat in categories" :key="cat.name" :label="cat.name" :value="cat.name" />
            </el-select>
          </el-form-item>

          <el-form-item label="排序">
            <el-input-number v-model="formData.sort_order" :min="0" />
          </el-form-item>

          <el-form-item label="状态">
            <el-switch v-model="formData.is_enabled" active-text="启用" inactive-text="禁用" />
          </el-form-item>
        </el-form>
      </template>
      <div v-else class="empty-state">
        <el-empty description="请选择或创建一个工具配置" />
      </div>
    </div>

    <el-dialog v-model="manageCategoriesDialog" title="分类管理" width="600px">
      <div class="category-manage">
        <el-button type="primary" size="small" @click="createNewCategory" style="margin-bottom: 16px">
          <el-icon><Plus /></el-icon> 新建分类
        </el-button>
        
        <el-table :data="categories" border>
          <el-table-column prop="name" label="分类名称" />
          <el-table-column prop="description" label="描述" />
          <el-table-column prop="sort_order" label="排序" width="80" />
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button link type="primary" size="small" @click="editCategory(row)">编辑</el-button>
              <el-button link type="danger" size="small" @click="deleteCategory(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <el-dialog v-model="categoryDialog" :title="categoryEditing ? '编辑分类' : '新建分类'" width="500px">
      <el-form :model="categoryForm" label-position="top">
        <el-form-item label="分类名称" required>
          <el-input v-model="categoryForm.name" placeholder="数据处理" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="categoryForm.description" placeholder="数据相关的工具" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="categoryForm.sort_order" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="categoryDialog = false">取消</el-button>
        <el-button type="primary" @click="saveCategory">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { Plus, Setting } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import toolApi from '@/services/toolConfig'

const loadingList = ref(false)
const configs = ref([])
const currentConfig = ref(null)
const isEditing = ref(false)
const categories = ref([])
const manageCategoriesDialog = ref(false)
const categoryDialog = ref(false)
const categoryEditing = ref(false)
const currentCategory = ref(null)

const formData = reactive({
  key: '',
  name: '',
  description: '',
  category: '',
  is_enabled: true,
  sort_order: 0
})

const categoryForm = reactive({
  name: '',
  description: '',
  sort_order: 0
})

const groupedTools = computed(() => {
  if (!Array.isArray(configs.value)) return []
  const groups = {}
  configs.value.forEach(tool => {
    if (!groups[tool.category]) {
      groups[tool.category] = []
    }
    groups[tool.category].push(tool)
  })
  
  const categoryOrder = {}
  categories.value.forEach((cat, idx) => {
    categoryOrder[cat.name] = cat.sort_order ?? idx
  })
  
  return Object.keys(groups)
    .sort((a, b) => (categoryOrder[a] ?? 999) - (categoryOrder[b] ?? 999))
    .map(cat => ({
      name: cat,
      tools: groups[cat]
    }))
})

const loadData = async () => {
  loadingList.value = true
  try {
    const [configsRes, catsRes] = await Promise.all([
      toolApi.getConfigs(),
      toolApi.getCategories()
    ])
    configs.value = configsRes.data
    categories.value = catsRes.data

    if (currentConfig.value?.id) {
      const updated = configs.value.find(c => c.id === currentConfig.value.id)
      if (updated) {
        selectConfig(updated)
      }
    }
  } catch (error) {
    ElMessage.error('加载数据失败: ' + error.message)
  } finally {
    loadingList.value = false
  }
}

const selectConfig = (config) => {
  currentConfig.value = config
  isEditing.value = true
  Object.assign(formData, {
    key: config.key,
    name: config.name,
    description: config.description,
    category: config.category,
    is_enabled: config.is_enabled,
    sort_order: config.sort_order
  })
}

const createNewConfig = () => {
  currentConfig.value = { id: null }
  isEditing.value = false
  Object.assign(formData, {
    key: '',
    name: '',
    description: '',
    category: '',
    is_enabled: true,
    sort_order: 0
  })
}

const saveConfig = async () => {
  if (!formData.key || !formData.name || !formData.category) {
    ElMessage.warning('请填写所有必填字段')
    return
  }

  try {
    if (isEditing.value && currentConfig.value.id) {
      await toolApi.updateConfig(currentConfig.value.id, formData)
      ElMessage.success('更新成功')
    } else {
      const res = await toolApi.createConfig(formData)
      currentConfig.value = res.data
      isEditing.value = true
      ElMessage.success('创建成功')
    }
    loadData()
  } catch (error) {
    ElMessage.error('保存失败: ' + (error.response?.data?.detail || error.message))
  }
}

const deleteConfig = () => {
  ElMessageBox.confirm('确定要删除这个工具配置吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await toolApi.deleteConfig(currentConfig.value.id)
      ElMessage.success('删除成功')
      currentConfig.value = null
      loadData()
    } catch (error) {
      ElMessage.error('删除失败: ' + (error.response?.data?.detail || error.message))
    }
  })
}

const createNewCategory = () => {
  currentCategory.value = null
  categoryEditing.value = false
  Object.assign(categoryForm, {
    name: '',
    description: '',
    sort_order: 0
  })
  categoryDialog.value = true
}

const editCategory = (category) => {
  currentCategory.value = category
  categoryEditing.value = true
  Object.assign(categoryForm, {
    name: category.name,
    description: category.description,
    sort_order: category.sort_order
  })
  categoryDialog.value = true
}

const saveCategory = async () => {
  if (!categoryForm.name) {
    ElMessage.warning('请填写分类名称')
    return
  }

  try {
    if (categoryEditing.value && currentCategory.value) {
      await toolApi.updateCategory(currentCategory.value.id, categoryForm)
      ElMessage.success('更新成功')
    } else {
      await toolApi.createCategory(categoryForm)
      ElMessage.success('创建成功')
    }
    categoryDialog.value = false
    loadData()
  } catch (error) {
    ElMessage.error('保存失败: ' + (error.response?.data?.detail || error.message))
  }
}

const deleteCategory = (category) => {
  ElMessageBox.confirm(`确定要删除分类"${category.name}"吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await toolApi.deleteCategory(category.id)
      ElMessage.success('删除成功')
      loadData()
    } catch (error) {
      ElMessage.error('删除失败: ' + (error.response?.data?.detail || error.message))
    }
  })
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.tool-config-container {
  display: flex;
  height: 100%;
  background: var(--el-bg-color-page);
}

.config-sidebar {
  width: 300px;
  background: var(--el-bg-color);
  border-right: 1px solid var(--el-border-color);
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color);
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  color: var(--el-text-color-primary);
}

.header-actions {
  display: flex;
  gap: 8px;
}

.config-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.category-group {
  margin-bottom: 16px;
}

.category-title {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  font-weight: 600;
  padding: 8px 12px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.config-item {
  padding: 12px;
  border-radius: 6px;
  cursor: pointer;
  margin-bottom: 8px;
  transition: all 0.2s;
  border: 1px solid var(--el-border-color-lighter);
  background: var(--el-bg-color);
}

.config-item:hover {
  background: var(--el-fill-color-light);
  border-color: var(--el-border-color);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.config-item.active {
  background: var(--el-color-primary-light-9);
  border-color: var(--el-color-primary);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.config-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.config-name {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.config-desc {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.config-main {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background: var(--el-bg-color);
  margin: 16px;
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-light);
}

.main-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--el-border-color);
}

.main-header h2 {
  margin: 0;
  font-size: 20px;
  color: var(--el-text-color-primary);
}

.config-form {
  max-width: 800px;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
</style>
